package com.khh.dao;

import com.khh.entity.Book;
import com.khh.entity.Student;
import lombok.Data;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by webrx on 2017-09-15.
 */
@Repository
@Data
public class BookDao {

    //name值是 applicationContext.xml 文件中工厂id名
    @Resource(name="sf")
    protected SessionFactory sf;

    //查询所有
    public List<Book> query(){
        Session session  = sf.openSession();
        return session.createQuery("from Book").list();
    }

   //添加数据
    public void insert(Book book){
        Session session  = sf.openSession();
        session.beginTransaction();
        session.save(book);
        session.getTransaction().commit();
        session.close();
    }

    //删除数据
    public void deleteById(int id){
        Session session  = sf.openSession();
        session.beginTransaction();
        //1.
        //session.delete(session.load(Book.class,id));
        //2.
        Query query = session.createQuery("delete Book where id=:id");
        query.setParameter("id",id);
        query.executeUpdate();
        session.getTransaction().commit();
        session.close();
    }

    //更新
    public void update(Book book, int id){
        Session session  = sf.openSession();
        session.beginTransaction();

        Book st = session.load(Book.class,id);
        st.setName(book.getName());
        st.setPrice(book.getPrice());
        session.saveOrUpdate(st);
        session.getTransaction().commit();
        session.close();
    }

    //查询byid
    public Book queryById(int id){
        Session session  = sf.openSession();
        Book book = session.get(Book.class, id);
        return book;
    }
}
